package cn.wolfcode.luowowo.website.util;

import cn.wolfcode.luowowo.cache.util.RedisKeys;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
    //添加cookie
    public static void addCookie(String name,String value,int time,HttpServletResponse response){
        Cookie c = new Cookie(name,value);
        c.setMaxAge(time);
        c.setPath("/");//默认共享路径是/xxx,如果遇到/xx/yy就不能共享了,所以要改
        response.addCookie(c);
    }

    //获取token
    public static String getToken(HttpServletRequest request, HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        String token =null;
        if(cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {
                if("token".equals(cookie.getName())){
                    token=cookie.getValue();
                    //延长浏览器中的cookie
                    cookie.setPath("/");
                    cookie.setMaxAge(RedisKeys.USER_LOGIN_TOKEN.getTime().intValue());
                    response.addCookie(cookie);
                    break;
                }
            }
        }
        return token;
    }
}
